import * as log4 from "log4js";
import * as path from "path";
import * as fs from "fs";
import { ipcMain, IpcMainInvokeEvent } from "electron";

class Logger4 {
    private logger: log4.Logger;

    constructor() {
        const logDir = path.join(process.cwd(), 'logs');
        if (!fs.existsSync(logDir)) {
            fs.mkdirSync(logDir, { recursive: true });
        }
        const logPath = path.join(logDir, "app.log");
        log4.configure({
            appenders: {
                out: { type: "stdout" },
                app: { type: "file", filename: logPath },
            },
            categories: {
                default: { appenders: ["out", "app"], level: "info" },
            },
        });
        this.logger = log4.getLogger();
    }
    initializeHandlers() {
        ipcMain.handle('log', this.handlerLog.bind(this));
        ipcMain.handle('error', this.handlerError.bind(this));
        ipcMain.handle('info', this.handlerInfo.bind(this));
        ipcMain.handle('warn', this.handlerWarn.bind(this));
    }
    handlerLog(_event: IpcMainInvokeEvent, ...message: any[]) {
        this.log(...message);
    }
    handlerError(_event: IpcMainInvokeEvent, ...message: any[]) {
        this.log(...message);
    }
    handlerInfo(_event: IpcMainInvokeEvent, ...message: any[]) {
        this.log(...message);
    }
    handlerWarn(_event: IpcMainInvokeEvent, ...message: any[]) {
        this.log(...message);
    }

    log(...message: any[]) {
        this.logger.info(...message as [any]);
    }
    error(...message: any[]) {
        this.logger.error(...message as [any]);
    }
    info(...message: any[]) {
        this.logger.info(...message as [any]);
    }
    warn(...message: any[]) {
        this.logger.warn(...message as [any]);
    }
}
export const logger4 = new Logger4();